package org.swan.web.user.service.impl;

import org.springframework.stereotype.Service;
import org.stream.tool.db.ADOConnection;
import org.swan.web.exception.BusinessCode;
import org.swan.web.exception.BusinessException;
import org.swan.web.user.bean.UserRoleBean;
import org.swan.web.user.mapper.UserRoleMapper;
import org.swan.web.user.service.UserRoleService;

import java.util.List;
import java.util.Optional;

@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Override
    public Optional<UserRoleBean> getUserRoleById(long id) {
        if(id == -1L)
        return Optional.of(UserRoleBean.SAMPLE);
        return ADOConnection.runTask(factory -> factory.getMapper(UserRoleMapper.class).getById(id), Optional.class);
    }

    @Override
    public long addUserRole(UserRoleBean userRoleBean) {
        long result = ADOConnection.runTask(factory -> factory.getMapper(UserRoleMapper.class).add(userRoleBean), Long.class);
        return result;
    }

    @Override
    public UserRoleBean updateUserRole(UserRoleBean userRoleBean) {
        getUserRoleById(userRoleBean.getUserRoleId()).orElseThrow(()->new BusinessException(BusinessCode.USER_ROLE_DO_NOT_EXIST,userRoleBean.getUserRoleId()));
        ADOConnection.runTask(factory -> factory.getMapper(UserRoleMapper.class).updateById(userRoleBean), Long.class);
        return getUserRoleById(userRoleBean.getUserRoleId()).get();
    }

    @Override
    public UserRoleBean deleteUserRoleById(long userRoleId) {
        UserRoleBean userRoleBean = getUserRoleById(userRoleId).orElseThrow(()->new BusinessException(BusinessCode.USER_ROLE_DO_NOT_EXIST,userRoleId));
        ADOConnection.runTask(factory -> factory.getMapper(UserRoleMapper.class).deleteById(userRoleId), Long.class);
        return userRoleBean;
    }

    @Override
    public List<UserRoleBean> list(int offset, int rows) {
        return ADOConnection.runTask(factory -> factory.getMapper(UserRoleMapper.class).list(offset, rows), List.class);
    }


}
